<template>
  <div id="watch" ref="watch">
    <report-card :open-dialog="dialog" v-on:closeDialog="dialog = false" :info="video" :type="1"></report-card>
    <v-container fluid>
      <v-row>
        <v-alert prominent class="mx-auto" type="error" v-if="errored">
          <v-row align="center">
            <v-col class="grow">
              <div class="title">Error!</div>
              <div>
                出错了！
              </div>
            </v-col>
            <v-col class="shrink">
              <v-btn @click="actions">重试</v-btn>
            </v-col>
          </v-row>
        </v-alert>
        <v-col v-else cols="11" class="mx-auto">
          <v-row>
            <v-col cols="12" sm="12" md="8" lg="8">
              <v-skeleton-loader type="card-avatar, article, actions" :loading="videoLoading" tile large>
                <div ref="hello">
                  <v-responsive max-height="450">
                    <video ref="videoPlayer" controls style="height: 100%; width: 100%">
                      <source :src="video.url" type="video/mp4" />
                    </video>
                  </v-responsive>

                  <v-card flat tile class="card">
                    <v-card-title class="pl-0 pb-0">{{
                      video.title
                    }}</v-card-title>
                    <div class="d-flex flex-wrap justify-space-between" id="btns">
                      <v-card-subtitle class="pl-0 pt-0 pb-0 subtitle-1" style="line-height: 2.4em;">
                        发布于 <v-icon>mdi-circle-small</v-icon>{{ dateFormatter(video.createTime) }}
                      </v-card-subtitle>
                      <v-card-actions class="pt-0 pl-0">
                        <v-btn text @click="like(video.videoId)"><v-icon :class="`pr-2${feeling == 'like'
                          ? ' red--text text--darken-1'
                          : ''
                          }`
                          ">mdi-thumb-up</v-icon>{{ video.goodCount }}</v-btn> <v-menu bottom left>
                          <template v-slot:activator="{ on }">
                            <v-btn icon v-on="on">
                              <v-icon>mdi-dots-vertical</v-icon>
                            </v-btn>
                          </template>

                          <v-list v-if="isAuthenticated">
                            <v-list-item @click="report()">
                              <v-list-item-title>
                                <v-icon>mdi-trash</v-icon>举报
                              </v-list-item-title>
                            </v-list-item>
                          </v-list>
                        </v-menu>
                        <!-- <v-btn
                          :href="`${url}/uploads/videos/${video.url}`"
                          text
                          class="grey--text text--darken-1"
                          ><v-icon>mdi-download</v-icon> Download</v-btn
                        > -->
                        <!-- <v-btn text class="grey--text text--darken-1"
                          ><v-icon>mdi-share</v-icon> Share</v-btn
                        >
                        <v-btn text class="grey--text text--darken-1"
                          ><v-icon>mdi-playlist-plus</v-icon> Save</v-btn
                        > -->
                      </v-card-actions>
                    </div>
                  </v-card>

                  <v-row class="justify-space-between">
                    <v-col cols="12" sm="6" md="5" lg="5">
                      <v-card class="transparent" flat>
                        <v-list-item three-line>
                          <v-list-item-avatar v-if="typeof video.userId !== 'undefined'" size="50">
                            <img v-if="video.avatar !== 'no-photo.jpg'" :src="video.avatar
                              " :alt="`${video.nickName} avatar`" />
                            <v-avatar v-else color="red">
                              <span class="white--text headline ">
                                {{
                                  video.nickName
                                    .split('')[0]
                                    .toUpperCase()
                                }}</span>
                            </v-avatar>
                          </v-list-item-avatar>
                          <v-list-item-content v-if="video.userId" class="align-self-auto">
                            <v-list-item-title class="font-weight-medium mb-1">{{ video.nickName }}</v-list-item-title>
                            <v-list-item-subtitle>{{ video.fansCount }} 粉丝
                            </v-list-item-subtitle>
                          </v-list-item-content>
                        </v-list-item>
                      </v-card>
                    </v-col>
                    <v-col cols="12" sm="6" md="4" lg="4">
                      <div class="d-flex justify-end align-center" v-if="typeof video.userId !== 'undefined'">
                        <v-btn v-if="
                          currentUser && video.userId !== currentUser.userId
                        " :class="[
                          { 'red white--text': !subscribed },
                          {
                            'grey grey--text lighten-3 text--darken-3': subscribed
                          },
                          'mt-6'
                        ]" tile large depressed :loading="subscribeLoading" @click="subscribe">{{ !subscribed ?
                          '关注' : '已关注' }}</v-btn>

                        <v-btn v-else-if="showSubBtn" :class="[
                          { 'red white--text': !subscribed },
                          {
                            'grey grey--text lighten-3 text--darken-3': subscribed
                          },
                          'mt-6'
                        ]" tile large depressed :loading="subscribeLoading" @click="subscribe">{{ !subscribed ?
                          '关注' : '已关注' }}</v-btn>

                        <!-- <v-btn
                          v-if="
                            video.userId && video.userId._id !== currentUser._id
                          "
                          :class="[
                            { 'red white--text': !subscribed },
                            {
                              'grey grey--text lighten-3 text--darken-3': subscribed
                            },
                            'mt-6'
                          ]"
                          tile
                          large
                          depressed
                          :loading="subscribeLoading"
                          @click="subscribe"
                          >{{ !subscribed ? 'subscribe' : 'subscribed' }}</v-btn
                        > -->
                        <!-- <v-btn icon class="ml-5 mt-6"
                          ><v-icon>mdi-bell</v-icon></v-btn
                        > -->
                      </div>
                    </v-col>
                    <v-col class="pl-11" offset="1" cols="11" md="11">
                      <p>
                        {{
                          truncate
                            ? truncateText(video.overview, 150)
                            : video.overview
                        }}
                      </p>
                      <v-btn text @click="show" class="remove-hover-bg">展开</v-btn>
                    </v-col>
                  </v-row>
                </div>
              </v-skeleton-loader>

              <v-row>
                <v-col v-if="video && video.status === 1">
                  <p class="mb-0">{{ video.commentCount }} 评论</p>

                  <AddComment @videoCommentLength="video.commentCount++" :videoId="video.videoId" />
                  <CommentList @videoCommentLength="video.commentCount--" :videoId="video.videoId"
                    @addCommentCount="video.commentCount++" />
                </v-col>
              </v-row>
            </v-col>

            <v-col cols="12" sm="12" md="4" lg="4">
              <hr class="grey--text" />
              <h4 class="mb-3 mt-3">猜你喜欢</h4>
              <div v-for="(video, i) in loading ? 12 : videos" :key="i" class="mb-5">
                <v-skeleton-loader class="mx-auto" type="list-item-avatar-three-line" :loading="loading" tile large>
                  <v-card class="card" tile flat v-if="!loading" :to="`/watch/${video.videoId}`">
                    <v-row no-gutters>
                      <v-col class="mx-auto" cols="12" sm="12" md="5" lg="5">
                        <!-- <v-responsive max-height="100%"> -->
                        <v-img class="align-center" height="110" :src="video.cover
                          ">
                        </v-img>
                        <!-- </v-responsive> -->
                      </v-col>
                      <v-col>
                        <div class="ml-2">
                          <v-card-title class="pl-2 pt-0 subtitle-1 font-weight-bold" style="line-height: 1">
                            {{ video.title }}
                          </v-card-title>

                          <v-card-subtitle class="pl-2 pt-2 pb-0" style="line-height: 1">
                            {{ video.nickName }}<br />
                            <v-icon>mdi-circle-small</v-icon>
                            {{ dateFormatter(video.createTime) }}
                          </v-card-subtitle>
                        </div>
                      </v-col>
                    </v-row>
                  </v-card>
                </v-skeleton-loader>
              </div>
              <!-- <v-col cols="12" sm="12" md="12" lg="12"> -->
              <infinite-loading :identifier="infiniteId" @infinite="getVideos">
                <div slot="spinner">
                  <v-progress-circular indeterminate color="red"></v-progress-circular>
                </div>
                <div slot="no-results"></div>
                <span slot="no-more"></span>
                <div slot="error" slot-scope="{ trigger }">
                  <v-alert prominent type="error">
                    <v-row align="center">
                      <v-col class="grow">
                        <div class="title">Error!</div>
                        <div>
                          出错了
                        </div>
                      </v-col>
                      <v-col class="shrink">
                        <v-btn @click="trigger">重试</v-btn>
                      </v-col>
                    </v-row>
                  </v-alert>
                </div>
              </infinite-loading>
              <!-- </v-col> -->
            </v-col>
          </v-row>
        </v-col>
      </v-row>
    </v-container>
    <signin-modal :openModal="signinDialog" :details="details" @closeModal="signinDialog = false" />
  </div>
</template>

<script>
import moment from 'moment'
import { mapGetters } from 'vuex'
import InfiniteLoading from 'vue-infinite-loading'
import { checkFollowing, following } from '../services/UserRequest'
import { list, watchVideo, likeVideo, isVideoLike } from '../services/VideoRequest'
// import SubscriptionService from '@/services/SubscriptionService'
// import FeelingService from '@/services/FeelingService'
//import HistoryService from '@/services/HistoryService'
import ReportCard from '@/components/ReportCard'
import SigninModal from '@/components/SigninModal'
import AddComment from '@/components/comments/AddComment'
import CommentList from '@/components/comments/CommentList'

export default {
  data: () => ({
    dialog: false,
    loading: false,
    loaded: false,
    errored: false,
    videoLoading: true,
    subscribed: false,
    subscribeLoading: false,
    showSubBtn: true,
    feeling: '',
    video: {},
    videoId: '',
    videos: [],
    page: 1,
    infiniteId: +new Date(),
    truncate: true,
    signinDialog: false,
    details: {}
  }),
  computed: {
    ...mapGetters(['currentUser', 'isAuthenticated'])
  },
  methods: {
    report() {
      this.dialog = true
    },
    async checkIsLike(id) {
      const isLike = await isVideoLike(id)
      if (!isLike) return
      this.video.isLiked = isLike.data.data
      if (this.video.isLiked) {
        this.feeling = 'like'
      } else {
        this.feeling = 'dislike'
      }
    },
    async getVideo(id) {
      this.errored = false
      this.videoLoading = true
      this.video = {}
      try {
        const video = await watchVideo(id)
        if (!video) return this.$router.push('/')
        this.video = video.data.data
      } catch (err) {
        this.errored = true
        console.log(err)
      } finally {
        this.videoLoading = false
        this.checkSubscription(this.video.userId)
        this.checkIsLike(this.video.videoId)
      }
      if (this.currentUser && this.currentUser.userId === this.video.userId) {
        this.showSubBtn = false
      } else {
        this.showSubBtn = true
      }
    },
    async getVideos($state) {
      this.errored = false
      if (!this.loaded) {
        this.loading = true
      }
      const videos = await list({ pageIndex: this.page, pageSize: 5 })
        .catch((err) => {
          console.log(err)
          this.errored = true
        })
        .finally(() => (this.loading = false))

      if (typeof videos === 'undefined') return

      if (videos.data.data.length) {
        this.page += 1

        this.videos.push(...videos.data.data)
        if ($state) {
          $state.loaded()
        }

        this.loaded = true
      } else {
        if ($state) {
          $state.complete()
        }
      }
    },
    async checkSubscription(id) {
      if (!this.isAuthenticated) return

      this.loading = true
      const sub = await checkFollowing(id)
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
        })

      console.log(sub.data.data)
      if (!sub) return

      if (!sub.data.data) this.subscribed = false
      else this.subscribed = true
    },
    async like(id) {
      if (!this.isAuthenticated) {
        if (!this.isAuthenticated) {
          this.signinDialog = true
          this.details = {
            title: '想要更多关于该博主的视频？',
            text: '登录即可关注该博主'
          }
          return
        }
      }
      this.loading = true
      const feeling = await likeVideo(id)
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
        })
      if (!feeling) return
      if (this.feeling == 'like') {
        this.feeling = 'dislike'
        this.video.goodCount--
      } else {
        this.feeling = 'like'
        this.video.goodCount++
      }
    },
    async subscribe() {
      if (!this.isAuthenticated) {
        this.signinDialog = true
        this.details = {
          title: '想要更多关于该博主的视频？',
          text: '登录即可关注该博主'
        }
        return
      }
      this.subscribeLoading = true
      const sub = await following(this.video.userId)
        .catch((err) => console.log(err))
        .finally(() => {
          this.subscribeLoading = false
        })

      if (!sub) return
      this.subscribed = !this.subscribed
      if (this.subscribed) {
        this.video.fansCount++
      } else {
        this.video.fansCount--
      }
      // if (!sub.data.data._id) {
      //   this.subscribed = false
      //   this.video.userId.subscribers--
      // } else {
      //   this.subscribed = true
      //   this.video.userId.subscribers++
      // }
    },
    play(e) {
      console.log(e)
    },
    actions() {
      this.getVideo()
    },
    show(event) {
      if (event.target.innerText === '展开') {
        this.truncate = false
        event.target.innerText = '收起'
      } else {
        this.truncate = true
        event.target.innerText = '展开'
      }
    },
    truncateText(string = '', num) {
      if (string.length <= num) {
        return string
      }
      return string.slice(0, num)
    },
    dateFormatter(date) {
      return moment(date).locale('zh-cn').fromNow()
    }
  },
  components: {
    ReportCard,
    AddComment,
    CommentList,
    SigninModal,
    InfiniteLoading
  },
  mounted() {
    this.getVideo(this.$route.params.id)

    if (this.isAuthenticated) this.checkIsLike(this.$route.params.id)
  },
  beforeRouteUpdate(to, from, next) {
    this.page = 1
      ; (this.loading = false), (this.loaded = false), (this.videos = [])
    this.infiniteId += 1
    this.getVideo(to.params.id)
    next()
  }
}
</script>

<style lang="scss">
video {
  max-width: 100%;
}

.grey-color {
  color: #7f7f7f !important;
}

#btns {
  border-bottom: 1px solid #e0d8d8;
}

button.v-btn.remove-hover-bg {
  background-color: initial !important;

  &:hover {
    background-color: #f9f9f9;
  }
}
</style>
